package com.example.lock;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @ClassName MyRedissonLock
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2019/8/4  14:24
 * @Version 1.0
 */

@Component
@Slf4j
public class MyRedissonLock implements Lock {

    @Autowired
    private RedissonClient redissonClient;

    private ThreadLocal<RLock> threadLocal = new ThreadLocal<RLock>();

    private static final String KEY = "REDISSON_KEY";


    @Override
    public void lock() {
        //1尝试获取锁
        if (tryLock()) {
            return;
        }

        //2.获取失败阻塞一会
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //3.递归尝试获取锁
        lock();
    }

    @Override
    public boolean tryLock() {
        RLock redissonClientLock = redissonClient.getLock(KEY);
        log.error(" --> " + redissonClientLock.isLocked());
        redissonClientLock.lock(30, TimeUnit.SECONDS);
        if (redissonClientLock.isLocked()) {
            log.error("加锁");
            threadLocal.set(redissonClientLock);
            return true;
        }
        return false;
    }

    @Override
    public void unlock() {
        log.error("解锁");
        threadLocal.get().unlock();
        threadLocal.remove();
    }


    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
